package com.walter.redis.tools.autoconfigure;

import com.walter.redis.tools.BloomFilterService;
import com.walter.redis.tools.autoconfigure.properties.BloomFilterProp;
import com.walter.redis.tools.autoconfigure.properties.RedisConfigProp;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * @author Walter
 * @date 2025/2/7 上午10:13
 **/
@EnableConfigurationProperties({BloomFilterProp.class})
@ConditionalOnProperty(prefix = "bloomfilter" , value = "enabled", havingValue = "true" )
@Slf4j
public class BloomFilterAutoConfiguration {
    @Resource
    private BloomFilterProp bloomFilterProp;
    @Resource
    RedisConfigProp redisConfigProp;

    @Bean
    public BloomFilterService bloomFilterService(RedissonClient redissonClient) {
        if(StringUtils.isBlank(bloomFilterProp.getBloomFilterName())){
            throw new IllegalStateException("布隆过滤器名称[bloomFilterName]参数值不能为空");
        }
        if(bloomFilterProp.getExpectedInsertions()<=0){
            throw new IllegalStateException("布隆过滤器预期值[expectedInsertions]参数值非法");
        }
        BloomFilterService bloomFilterService = new BloomFilterService(redissonClient,bloomFilterProp.getBloomFilterName(), bloomFilterProp.getExpectedInsertions(), bloomFilterProp.getFalsePositiveProbability());
        log.info("BloomFilterAutoConfiguration initialized");
        return bloomFilterService;
    }

    @Bean
    public RedissonClient redissonClient() {
        // 配置 Redisson 客户端 (需要根据你的 Redis 服务器配置进行修改)
        org.redisson.config.Config config = new org.redisson.config.Config();
        String address = "redis://" + redisConfigProp.getHost() + ":" + redisConfigProp.getPort();
        config.useSingleServer().setAddress(address);
        config.useSingleServer().setPassword(redisConfigProp.getPassword());
        config.useSingleServer().setDatabase(redisConfigProp.getDatabase());
        return org.redisson.Redisson.create(config);
    }
}
